<?php
// Copyright 2019 Hackware SpA <human@hackware.cl>
// This file is part of "Hackware Web Services Wallet" and licensed under
// the terms of the GNU Affero General Public License version 3, or (at your
// option) a later version. You should have received a copy of this license
// along with the software. If not, see <https://www.gnu.org/licenses/>.

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class ChangeWalletUidToUserUid extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('wallets', function (Blueprint $table) {
            $table->renameColumn('uid', 'user_uid');
        });

        // Looks like renaming a column gets executed after any other
        // operation, by separating functions I'm sure the column has
        // already been renamed.
        Schema::table('wallets', function (Blueprint $table) {
            $table->foreign('user_uid')
                ->references('uid')
                ->on('users')
                ->onUpdate('cascade')
                ->onDelete('restrict');
        });

        Schema::table('transactions', function (Blueprint $table) {
            $table->dropForeign(['wallet_uid']);
            $table->renameColumn('wallet_uid', 'user_uid');
        });

        Schema::table('transactions', function (Blueprint $table) {
            $table->foreign('user_uid')
                ->references('uid')
                ->on('users')
                ->onUpdate('cascade')
                ->onDelete('restrict');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('wallets', function (Blueprint $table) {
            $table->dropForeign(['user_uid']);
            $table->renameColumn('user_uid', 'uid');
        });

        Schema::table('transactions', function (Blueprint $table) {
            $table->dropForeign(['user_uid']);
            $table->renameColumn('user_uid', 'wallet_uid');
        });

        Schema::table('transactions', function (Blueprint $table) {
            $table->foreign('wallet_uid')
                ->references('uid')
                ->on('wallets')
                ->onUpdate('cascade')
                ->onDelete('restrict');
        });
    }
}
